<template>
  <div class="login-box">
    <h2>login</h2>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="authCode" class="codeBox">
        <el-input v-model.number="ruleForm.authCode"></el-input>
        <el-button @click="getAuth" type="primary">获取验证码</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getAuthCode, Login } from "../api";
import { mapMutations } from "vuex";
import { UserInfo } from "../utils";
export default {
  data() {
    return {
      ruleForm: {},
      rules:{
        username:[{required:true,message:'请输入账号',trigger:'blur'}],
        password:[{required:true,message:'请输入密码',trigger:'blur'}],
        authCode:[
          {required:true,message:'请输入验证码',trigger:'blur'}
        ]
      }
    };
    
  },
  methods: {
    ...mapMutations(["CHANGE_ROUTER_LIST", "CHANGE_USER_INFO"]),
    submitForm(formName) {
      this.$refs[formName].validate((valid)=>{
        if(valid){
          Login(this.ruleForm).then((res)=>{
            console.log(res)
            localStorage.setItem('token',res.data);
            this.$message.success(res.msg)
            UserInfo()
            this.$router.push('/')
          })
        }else{
          console.log('error submit')
          return false;
        }
      })
    },
    getAuth(){
      getAuthCode().then((res)=>{
        this.$message({message:`验证码为：${res.data}`});
      })
    }
  },
};
</script>
<style lang="scss" scoped>
  .login-box{
    width: 500px;
    border: 1px solid #ccc;
    border-radius: 10px;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
  .codeBox{
    ::v-deep .el-form-item__content{
      display: flex;
    }
  }
</style>